#!/usr/bin/env python
#coding:utf-8

import tornado
from ..baseHandler import BaseHandler
from bson import ObjectId
from ..error import ErrorHandler

class OwnerHandler(BaseHandler):
    #获取个人主页的相关数据信息
    @tornado.gen.coroutine
    def get(self,userId):
        if not userId:
            return ErrorHandler.write_error(self,status_code=101,message="缺少用户ID信息")
        try:
            objectId = ObjectId(userId)
        except Exception as e:
            return  ErrorHandler.write_error(self,status_code=102,message=str(e))
        #若有传递用户ID则返回用户个人信息
        #1、首先获取用户基本信息
        userInfo = {}
        user_info = yield self.db.user.find_one({'_id':objectId},{'session_token':0,'token':0,'password':0})
        if user_info:
            pass
        else:
            return ErrorHandler.write_error(self,status_code=102,message="用户信息异常,请稍后重试")

        #2、后面获取消息信息
        message_info = yield self.db.message.find({'user':userId,'read':False}).count()
        user_info['message'] = message_info

        #3、获取积分总数
        points = yield self.db.points.find_one({'user':userId})
        if points:
            user_info['points'] = points['number']
        else:
            user_info['points'] = 0

        #4、coupon优惠券信息获取
        coupon = yield self.db.coupon.find({'user':userId}).count()
        user_info['coupon_count'] = coupon

        #5、获取销售数量
        sales = yield self.db.user_sales.find_one({'user':userId})
        if sales:
            user_info['sales_count'] = sales['total']
        else:
            user_info['sales_count'] = 0

        #6、收藏相关信息问题
        collection = yield self.db.user_collection.find({'user':userId}).count()
        user_info['collection_count'] = collection

        #7、评价相关信息
        comments = yield self.db.user_comment.find_one({'user':userId})
        if comments:
            user_info['comments_count'] = comments['comment_count']
        else:
            user_info['comments_count'] = 0

        #8、我的收益相关
        user_info['profit'] = 0

        #组织完所有数据，返回数据
        return self.response_msg(200,"个人信息获取成功",self.find_formart(user_info))


handlers = [(r"/owner/(.*)",OwnerHandler),
            ]